package org.zjt.helloworld;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import org.zjt.helloworld.domain.RequestMsgProto;
import org.zjt.helloworld.domain.ResponseMsgProto;

/**
 * Created by zhangjuntao on 2017/3/16.
 */
public class SubReqServerHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RequestMsgProto.Request req = (RequestMsgProto.Request) msg;
        System.out.println("Service accept client subscribe req : [" + req.toString() + "]");


        ctx.writeAndFlush(createResponce());
    }


    public static ResponseMsgProto.Response createResponce(){
        ResponseMsgProto.Response.Builder builder = ResponseMsgProto.Response.newBuilder();
        builder.setResponseType(ResponseMsgProto.Response.ResponseType.SUCCESS);
        ResponseMsgProto.Response.ResponseData.Builder dataBuilder = ResponseMsgProto.Response.ResponseData.newBuilder();
        dataBuilder.setName("request");
        dataBuilder.setValue(112);
        builder.addData(dataBuilder);
        builder.addHttpCode(222);
        return builder.build();
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();// 发生异常，关闭链路
    }
}
